package com.hongfeng.support.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hongfeng.support.item.ParmItem;
import com.hongfeng.support.item.QueryItem;
import com.hongfeng.support.item.tag.FieldOperator;
import com.hongfeng.support.model.Menu;
import com.hongfeng.support.model.Purview;
import com.hongfeng.support.service.MenuService;
import com.hongfeng.support.service.PurviewService;
import com.hongfeng.support.service.common.impl.GenericServiceImpl;

@Service
public class MenuServiceImpl extends GenericServiceImpl<Menu, Long> implements
		MenuService {

	@Resource
	private PurviewService purviewService;

	public MenuServiceImpl() {
		super(Menu.class);
	}

	@Override
	public Menu read(Long id) {
		Menu menu = super.read(id);
		Long pid = menu.getPid();
		if (pid != null) {
			menu.setParentMenu(super.read(pid));
		}
		return menu;
	}

	@Override
	public List<Menu> findAll() {
		return this.findAll(new QueryItem(Menu.class));
	}

	@Override
	public List<Menu> findAll(QueryItem item) {
		List<Menu> menus = super.findAll(item);
		for (Menu menu : menus) {
			if (menu.getPid() != null) {
				for (Menu m : menus) {
					if (menu.getPid().longValue() == m.getId().longValue()) {
						menu.setParentMenu(m);
						break;
					}
				}
			}
		}
		return menus;
	}

	/**
	 * 删除菜单及设置子菜单的父菜单为空
	 * 
	 * @param ids
	 *            要删除的菜单ID，id之间以","隔开
	 */
	public void deleteMenuWithRelation(String ids) {
		String[] idsArr = ids.split(",");
		for (String idStr : idsArr) {
			Long id = Long.parseLong(idStr);
			
			QueryItem item = new QueryItem(Menu.class);
			item.addCondition("pid", FieldOperator.EQUAL, id);
			List<Menu> menus = findAll(item);
			for (Menu menu : menus) {
				menu.setPid(null);
				update(menu);
			}
			
			ParmItem parmItem = new ParmItem("menu.id", id, FieldOperator.EQUAL);
			List<Purview> purviews = purviewService.findAllByQuery(
					Purview.class, parmItem);
			for (Purview purview : purviews) {
				purviewService.delete(purview.getId());
			}
			
			delete(id);
		}
	}

}
